<template>
  <div class="flex">
    <el-select v-model="addressDTO.provinceCode" class="flex-item" placeholder="请选择" v-if="isShowAreaLevel >= 1"
      @change="handleSelectArea(1)">
      <el-option v-for="item in initAddressData.provinceData" :key="item.areaCode" :label="item.areaName"
        :value="item.areaCode" />
    </el-select>
    <div class="width-12" />
    <el-select v-model="addressDTO.cityCode" class="flex-item" placeholder="请选择" v-if="isShowAreaLevel >= 2"
      @change="handleSelectArea(2)">
      <el-option v-for="item in initAddressData.cityData" :key="item.areaCode" :label="item.areaName"
        :value="item.areaCode" />
    </el-select>
    <div class="width-12" />
    <el-select v-model="addressDTO.districtCode" class="flex-item" placeholder="请选择" v-if="isShowAreaLevel >= 3"
      @change="handleSelectArea(3)">
      <el-option v-for="item in initAddressData.districtData" :key="item.areaCode" :label="item.areaName"
        :value="item.areaCode" />
    </el-select>
    <div class="width-12" />
    <el-select v-model="addressDTO.streetCode" class="flex-item" placeholder="请选择" v-if="isShowAreaLevel >= 4">
      <el-option v-for="item in initAddressData.streetData" :key="item.areaCode" :label="item.areaName"
        :value="item.areaCode" />
    </el-select>
  </div>
</template>

<script lang="ts">
  import {
    defineComponent,
    onMounted,
    ref,
    watch
  } from 'vue'
  import {
    listAreaByParentId,
    getAreaList
  } from '@/api/common/common'
  export default defineComponent({
    name: 'AddressSelected',
    props: {
      selectedAreaCall: Function
    },
    setup(props) {
      const isShowAreaLevel = ref(3)
      const addressDTO = ref({
        provinceCode: '',
        provinceName: '',
        cityCode: '',
        cityName: '',
        districtCode: '',
        districtName: '',
        streetCode: '',
        streetName: '',
        // 是否海外：0-国内；1-国外
        isOverseas: 0,
        addressName: ''
      })

      const allProvinceData = ref([])
      const allCityData = ref([])
      const allDistrictData = ref([])
      const allStreetData = ref([])

      const initAddressData = ref({
        provinceData: [],
        cityData: [],
        districtData: [],
        streetData: []
      })
      const showIsOverseas = ref(null)
      const allArea = ref([])
      onMounted(() => {
        // getAreaListByParentId(0, 1, () => {

        // })
        // loadAllArea()
        setAddress()
      })
      const loadAllArea = () => {
        let areaParams = {
          isOverseas: showIsOverseas.value
        }
        allProvinceData.value = []
        allCityData.value = []
        allDistrictData.value = []
        allStreetData.value = []
        getAreaList(areaParams).then(response => {
          if (response.isError) return
          response.data.forEach((item) => {
            if (item.areaLevel === 1) {
              allProvinceData.value.push(item)
            }
            if (item.areaLevel === 2) {
              allCityData.value.push(item)
            }
            if (item.areaLevel === 3) {
              allDistrictData.value.push(item)
            }
            if (item.areaLevel === 4) {
              allStreetData.value.push(item)
            }
          })
          getAreaListByParentId(0, 1, () => {

          })
        })
      }

      const getAreaListByParentId = (parentId: number, level: number, callback: Function) => {
        listAreaByParentId(parentId).then(response => {
          if (response.isError) return
          if (level == 1) {
            initAddressData.value.provinceData = response.data
          } else if (level == 2) {
            initAddressData.value.cityData = response.data
          } else if (level == 3) {
            initAddressData.value.districtData = response.data
          } else if (level == 4) {
            initAddressData.value.streetData = response.data
          }
          cleartAreaData(level)
          callback()
        })
        // if (level === 1) {
        //   initAddressData.value.provinceData = allProvinceData.value
        // } else if (level === 2) {
        //   initAddressData.value.cityData = allCityData.value.filter((item) => item.parentId === parentId)
        // } else if (level === 3) {
        //   initAddressData.value.districtData = allDistrictData.value.filter((item) => item.parentId ===
        //     parentId)
        // } else if (level === 4) {
        //   initAddressData.value.streetData = allStreetData.value.filter((item) => item.parentId === parentId)
        // }
        // cleartAreaData(level)
      }
      // 清除地区数据
      const cleartAreaData = (level: number) => {
        if (level == 1) {
          initAddressData.value.cityData = []
          initAddressData.value.districtData = []
          initAddressData.value.streetData = []
        } else if (level == 2) {
          initAddressData.value.districtData = []
          initAddressData.value.streetData = []
        } else if (level == 3) {
          initAddressData.value.streetData = []
        } else if (level == 4) {}
      }

      const clearSelectArea = (level: number) => {
        if (level == 1) {
          addressDTO.value.cityCode = ''
          addressDTO.value.cityName = ''
          addressDTO.value.districtCode = ''
          addressDTO.value.districtName = ''
          addressDTO.value.streetCode = ''
          addressDTO.value.streetName = ''
        } else if (level == 2) {
          addressDTO.value.districtCode = ''
          addressDTO.value.districtName = ''
          addressDTO.value.streetCode = ''
          addressDTO.value.streetName = ''
        } else if (level == 3) {
          addressDTO.value.streetCode = ''
          addressDTO.value.streetName = ''
        } else if (level == 4) {}
      }

      const handleSelectArea = (level: number) => {
        const parentId = ref(null)
        if (level == 1) {
          let areaObj = initAddressData.value.provinceData.find(function(item) {
            return item.areaCode === addressDTO.value.provinceCode
          })
          if (areaObj != null) {
            parentId.value = areaObj.areaId
            addressDTO.value.provinceName = areaObj.areaName
            addressDTO.value.isOverseas = areaObj.isOverseas
            if (areaObj.isOverseas === 1) {
              // 海外，增加显示4级
              isShowAreaLevel.value = 4
            } else {
              isShowAreaLevel.value = 3
            }
          }
        } else if (level == 2) {
          let areaObj = initAddressData.value.cityData.find(function(item) {
            return item.areaCode === addressDTO.value.cityCode
          })
          if (areaObj != null) {
            parentId.value = areaObj.areaId
            addressDTO.value.cityName = areaObj.areaName
          }
        } else if (level == 3) {
          let areaObj = initAddressData.value.districtData.find(function(item) {
            return item.areaCode === addressDTO.value.districtCode
          })
          if (areaObj != null) {
            parentId.value = areaObj.areaId
            addressDTO.value.districtName = areaObj.areaName
          }
        } else if (level == 4) {
          let areaObj = initAddressData.value.streetData.find(function(item) {
            return item.areaCode === addressDTO.value.streetCode
          })
          if (areaObj != null) {
            addressDTO.value.streetName = areaObj.areaName
          }

        }
        clearSelectArea(level)
        assemblePCDSName()
        if (parentId.value != null) {
          getAreaListByParentId(parentId.value, level + 1, () => {

          })
        }
      }
      // 设置是否地区数据：空就显示全部，0-国内，1-国外
      // const setIsOverseas = (isOverseas: number) => {
      //   showIsOverseas.value = isOverseas
      //   loadAllArea()
      // }

      // 设置地址信息
      // isShowLevel：显示级别：1-省级，2-市级，3-地区级，4-街道级
      const setAddress = (isShowLevel: number, pCode: string, cCode: string, dCode: string,
        sCode: string) => {
        isShowAreaLevel.value = isShowLevel ? isShowLevel : 3
        addressDTO.value.provinceCode = pCode
        addressDTO.value.provinceName = ''
        addressDTO.value.cityName = ''
        addressDTO.value.districtName = ''
        addressDTO.value.streetName = ''
        if (pCode) {
          const province = ref({})
          if (initAddressData.value.provinceData && initAddressData.value.provinceData.length > 0) {
            province.value = initAddressData.value.provinceData.find((item) => {
              return item.areaCode === pCode
            })
            if (province.value) {
              setCityDistractStreet(province.value, cCode, dCode, sCode)
            }
          } else {
            // 根据省份id，获取城市列表
            getAreaListByParentId(0, 1, () => {
              province.value = initAddressData.value.provinceData.find((item) => {
                return item.areaCode === pCode
              })
              if (province.value) {
                setCityDistractStreet(province.value, cCode, dCode, sCode)
              }
            })
          }
        } else {
          getAreaListByParentId(0, 1, () => {})
        }
      }

      const setCityDistractStreet = (province: any, cCode: string, dCode: string, sCode: string) => {
        if (province != null) {
          addressDTO.value.provinceName = province.areaName
          // 根据省份id，获取城市列表
          getAreaListByParentId(province.areaId, 2, () => {
            // 判断是否有城市编码和城市列表数据
            if (cCode && initAddressData.value.cityData) {
              let city = initAddressData.value.cityData.find((item) => {
                return item.areaCode === cCode
              })
              if (city) {
                addressDTO.value.cityName = city.areaName
                // 根据城市id，获取区县列表
                getAreaListByParentId(city.areaId, 3, () => {
                  if (dCode && initAddressData.value.districtData) {
                    let district = initAddressData.value.districtData.find((item) => {
                      return item.areaCode === dCode
                    })
                    if (district) {
                      addressDTO.value.districtName = district.areaName
                      // 根据区县id，获取区县列表
                      getAreaListByParentId(district.areaId, 4, () => {
                        if (sCode && initAddressData.value.streetData) {
                          let street = initAddressData.value.streetData.find((item) => {
                            return item.areaCode === dCode
                          })
                          if (street) {
                            addressDTO.value.streetName = street.areaName
                            assemblePCDSName()
                          }
                        }
                      })
                    }
                  }
                  assemblePCDSName()
                })
              }
            }
            assemblePCDSName()
          })
        }
        addressDTO.value.cityCode = cCode
        addressDTO.value.districtCode = dCode
        addressDTO.value.streetCode = sCode
        assemblePCDSName()
      }



      // 组装省市区县街道名称
      const assemblePCDSName = () => {
        const addressName = ref('')
        if (addressDTO.value.provinceName) {
          if (addressName.value.length > 0) {
            addressName.value += ' '
          }
          addressName.value += addressDTO.value.provinceName
        }
        if (addressDTO.value.cityName) {
          if (addressName.value.length > 0) {
            addressName.value += ' '
          }
          addressName.value += addressDTO.value.cityName
        }
        if (addressDTO.value.districtName) {
          if (addressName.value.length > 0) {
            addressName.value += ' '
          }
          addressName.value += addressDTO.value.districtName
        }
        if (addressDTO.value.streetName) {
          if (addressName.value.length > 0) {
            addressName.value += ' '
          }
          addressName.value += addressDTO.value.streetName
        }
        addressDTO.value.addressName = addressName.value.length > 0 ? addressName.value : ''

        // 选择回调函数
        props.selectedAreaCall(addressDTO.value)
      }
      return {
        isShowAreaLevel,
        addressDTO,
        initAddressData,
        handleSelectArea,
        setAddress
      }
    }
  })
</script>

<style lang="scss" scoped>
  $darkBlue: #182245;
</style>
